package dnl.utils.jdbc.impexp;

import dnl.persistence.CsvToJdbcImporter;
import dnl.persistence.JdbcToCsv;
import dnl.persistence.JdbcToolz;
import dnl.persistence.TableInfo;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 * @author Daniel Orr
 */
public class JdbcImport {

    private static final Logger logger = LoggerFactory.getLogger(JdbcImport.class);

    private DataSource dataSource;

    private MetadataRegistry metadataRegistry;


    public JdbcImport(DataSource dataSource, File exportDir) {
        this.dataSource = dataSource;
        metadataRegistry = MetadataRegistry.fromFile(exportDir);
    }

    public Set<String> getTableNames() {
        return metadataRegistry.getTableNames();
    }

    public void importTableData() throws SQLException, IOException {
        logger.debug("Acquiring a connection.");
        final Connection connection = dataSource.getConnection();
        final Set<String> tableNames = getTableNames();
        logger.debug("Start processing {} tables.", tableNames.size());

        CsvToJdbcImporter importer = new CsvToJdbcImporter(dataSource);

        for (String tableName : tableNames) {
            final TableInfo ti = metadataRegistry.getTableInfo(tableName);
            importer.importCsv(ti, metadataRegistry.getFileForTable(tableName));
        }
    }
}
